import { EditorRender, JSONContent, useEditor } from '@gitee/tide';
import { StarterKit } from '@gitee/tide-starter-kit';
import { memo, useEffect, useImperativeHandle, useRef } from 'react';
import { IEditRef } from '../../types';
import { useUpload } from '../../utils/upload';


/**
 * 富文本控件
 */
type IRichEdit = {
    content: string;
    onRef: React.MutableRefObject<IEditRef | undefined>;
}
const RichEdit = ({ content, onRef }: IRichEdit) => {
    const richEditContentRef = useRef<string>();
    /**
    * 向外暴露方法,获取到文本内的值
    */
    useImperativeHandle(onRef, () => ({
        getData: () => {
            return richEditContentRef.current
        }
    }));
    const upload = useUpload();

    /**
     * 富文本上传图片的回调
     */
    const imageUpload = async (file: File, progressCallback: (progress: number) => void) => {

        const formData = new FormData();
        formData.append("file", file);
        const result = await upload('https://yjws.jxhzszkj.com/firecheck/base/uploadFileToLocal', {
            data: {
                file
            },
        });
        return Promise.resolve(result);
    }


    useEffect(() => {
        if (content) {
            //动态设置富文本内容
            editor?.setContent(JSON.parse(content))
        }
    }, [content])

    const editor = useEditor({
        extensions: [StarterKit.configure({
            taskItem: {
                onReadOnlyChecked: () => true,
            },
            uploader: {
                image: {
                    uploader: imageUpload,
                },
            },
        })],
        content: "",
        fullscreen: false,

        onChange: (doc, edit) => { richEditContentRef.current = edit.getHTML() },
    });
    return <EditorRender editor={editor} />;
}


export default memo(RichEdit);